import { RECORDER_CONFIG } from "../config";
import { COS_TYPE } from "../enum/pd-enum";
import { upload2cos } from "./upload-cos";
import type { WxRecorderOnStopRes } from "./wx-types";

let recorderManager: UniApp.RecorderManager;

type StartOps = {
	uploadCallBack : (p : {cosUrl : string}) => void;
}

//缓存传入的配置项，以便在后续环节中调用
let cacheOps : StartOps | undefined;

const recorderStart = (ops ?: StartOps) => {
	if (!recorderManager) {
		recorderManager = uni.getRecorderManager();
	};
	ops && (cacheOps = ops);
	recorderManager.start(RECORDER_CONFIG);
	recorderManager.onStop(stopHandler);
};


const recorderStop = () => {
	recorderManager && recorderManager.stop();
	cacheOps = undefined;
};


const stopHandler = (res: WxRecorderOnStopRes) => {
	upload2cos({
		type : COS_TYPE.business,
		filePath : res.tempFilePath
	}).then(res => {
		if (!cacheOps || !cacheOps.uploadCallBack) return;
		cacheOps.uploadCallBack(res);
	});
	
	cacheOps && recorderStart(cacheOps);
};


export namespace Recorder {
	export const start = recorderStart;
	export const stop = recorderStop;
}